#include <system.h>
#include <sdram_test.h>
#include <io.h>
#include <stdio.h>

static void
do_sdram_test(int *_correct, int *_total) {
    int i;
    int value = 0x232323, delta = 1;
    int correct = 0, total = 0;
    for (i = SDRAM_BASE; i <= SDRAM_END; i += 4) {
        int *addr = (int*)(i + 0xc0000000);
        IOWR_32DIRECT(addr, 0, value);
        value += delta;
        delta ++;
    }
    value = 0x232323; delta = 1;
    for (i = SDRAM_BASE; i <= SDRAM_END; i += 4) {
        int *addr = (int*)(i + 0xc0000000);
        int read_value = IORD_32DIRECT(addr, 0);
        if (value == read_value)
            ++correct;
        ++total;
        value += delta;
        delta ++;
    }
    *(_correct) += correct;
    *(_total) += total;
    /*
    if (correct == total) {
        cprintf("passed sdram test!\n");
    } else {
        cprintf("failed in sdram test!\n");
    }
    */
}

void
sdram_test() {
#ifdef SDRAM_BASE
    int correct = 0, total = 0;
    do_sdram_test(&correct, &total);
    if (correct == total) {
        int _t;
        for (_t = 0; _t < 0; ++_t)
            do_sdram_test(&correct, &total);
    }
    cprintf("sdram test: total %d, correct %d, correct_ratio %d%% ", total, correct, correct * 100 / total);
    if (correct == total)
        cprintf("passed!\n");
    else
        cprintf("failed!\n");
#else
    cprintf("sdram test: sdram not found!\n");
#endif
}
